package com.ck.company.controller;

import com.ck.cache.RedisCacheDao;
import com.ck.company.service.*;
import com.ck.config.CustomProperties;
import com.ck.constant.*;
import com.ck.model.common.Program;
import com.ck.model.common.ScreenCanvasMapping;
import com.ck.model.common.User;
import com.ck.model.common.sys.JsonResponse;
import com.ck.model.common.sys.LoginUser;
import com.ck.model.company.dto.CpProgramDTO;
import com.ck.model.company.vo.CpProgramDeviceCountVO;
import com.ck.model.company.vo.CpProgramDeviceListVO;
import com.ck.model.company.vo.CpProgramListVO;
import com.ck.model.company.vo.CpProgramTemplateVO;
import com.ck.util.SessionUtils;
import com.github.pagehelper.Page;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

/**
 * 商家-节目
 *
 * @author linqiang
 * @date 2018-06-20 18:19
 */
@Controller
@RequestMapping(value = "/cpProgram")
public class CpProgramController {
    private Logger logger = LoggerFactory.getLogger(CpProgramController.class);
    @Autowired
    private CpProgramService cpProgramService;
    @Autowired
    private CpDeviceInfoService cpDeviceInfoService;
    @Autowired
    private CpPictureService cpPictureService;
    @Autowired
    private CpVideoService cpVideoService;
    @Autowired
    private CpProgramTemplateService cpProgramTemplateService;

    @Autowired
    private CpScreenCanvasMappingService cpScreenCanvasMappingService;
    @Autowired
    private RedisCacheDao redisCacheDao;
    @Autowired
    private CustomProperties customProperties;

    /**
     * 跳转到创建节目前选择节目模板的列表页面
     *
     * @return string
     */
    @RequestMapping(value = "/toAddProgramPage")
    public String toAddProgramPage(String templateName, Integer type, Model model, Integer pageNum, Integer pageSize, HttpServletRequest request) {
        try {
            User user = (User) request.getSession().getAttribute(RequestConstant.SESSION_KEY_USER);
            pageNum = (pageNum == null ? PageConstant.DEFAULT_PAGE_NUM : pageNum);
            pageSize = (pageSize == null ? PageConstant.DEFAULT_PAGE_SIZE : pageSize);
            Page<CpProgramTemplateVO> page = cpProgramTemplateService.listByPage(user.getCompanyCode(),templateName, type, pageNum, pageSize);
            List<ScreenCanvasMapping> list = cpScreenCanvasMappingService.list();
            //token
            Object token = redisCacheDao.getCache(CacheConstant.CK_TOKEN_USER_MAPPING, user.getUserName());
            model.addAttribute("screenCanvasMappingList", (list == null ? new ArrayList<>() : list));
            model.addAttribute("pageNum", pageNum);
            model.addAttribute("pageSize", pageSize);
            model.addAttribute("result", page.getResult());
            model.addAttribute("total", page.getTotal());
            model.addAttribute("templateName", templateName);
            model.addAttribute("type", type);
            model.addAttribute("token", token);
            model.addAttribute("clientDomain", customProperties.getProgramEditClientDomain());

        } catch (Exception e) {
            e.printStackTrace();
            logger.error("CpProgramController toAddProgramPage 转到创建节目前选择节目模板的列表页面失败:" + e.getMessage());
        }
        return "cp/cp_program_create";
    }

    /**
     * 跳转到预览页面
     *
     * @param programId 节目ID
     * @param model     模型
     * @return 页面
     */
    @RequestMapping(value = "/toSimulatorPage")
    public String toSimulatorPage(Long programId, Model model) {
        try {
            model.addAttribute("programId", programId);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("CpProgramController toSimulatorPage fail: " + e.getMessage());
        }
        return "cp/cp_program_simulator";
    }

    /**
     * 商家节目列表分页查询
     *
     * @param programName   节目名称
     * @param programStatus 节目状态
     * @param model         模型
     * @param pageNum       当前页
     * @param pageSize      每页条数
     * @return 列表页面
     */
    @RequestMapping(value = "/listByPage")
    public String listByPage(String programName, Integer programStatus, Model model, Integer pageNum, Integer pageSize,
                             HttpServletRequest request) {
        try {
            User user = (User) request.getSession().getAttribute(RequestConstant.SESSION_KEY_USER);
            pageNum = (pageNum == null ? PageConstant.DEFAULT_PAGE_NUM : pageNum);
            pageSize = (pageSize == null ? PageConstant.DEFAULT_PAGE_SIZE : pageSize);
            Page<CpProgramListVO> page = cpProgramService.listByPage(user.getCompanyCode(), programName, programStatus,
                    pageNum, pageSize);
            //token
            Object token = redisCacheDao.getCache(CacheConstant.CK_TOKEN_USER_MAPPING, user.getUserName());
            model.addAttribute("pageNum", pageNum);
            model.addAttribute("pageSize", pageSize);
            model.addAttribute("result", page.getResult());
            model.addAttribute("total", page.getTotal());
            model.addAttribute("programName", programName);
            model.addAttribute("programStatus", programStatus);
            model.addAttribute("token", token);
            model.addAttribute("clientEditDomain", customProperties.getProgramEditClientDomain());
            model.addAttribute("clientPushDomain", customProperties.getProgramPushClientDomain());
            model.addAttribute("clientCheckDomain", customProperties.getProgramCheckClientDomain());
            model.addAttribute("clientVerifyDomain", customProperties.getProgramVerifyClientDomain());
            model.addAttribute("clientDetailDomain", customProperties.getProgramDetailClientDomain());
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("CpProgramController listByPage fail:" + e.getMessage());
        }
        return "cp/cp_program_list";
    }

    /**
     * 创建节目(空节目，未上传素材)
     *
     * @param programName       节目名称
     * @param programResolution 节目分辨率
     * @param programTemplateId 模板ID
     * @param request
     * @return
     */
    @RequestMapping(value = "/saveProgram")
    @ResponseBody
    public Object saveProgram(String programName, String programResolution, Long programTemplateId, HttpServletRequest request) {
        if (StringUtils.isBlank(programName)) {
            return new JsonResponse(ResponseConstant.CODE_FAIL, ProgramConstant.MSG_PROGRAM_NAME_NOT_NULL);
        }
        if (StringUtils.isBlank(programResolution)) {
            return new JsonResponse(ResponseConstant.CODE_FAIL, ProgramConstant.MSG_PROGRAM_RESOLUTION_NOT_NULL);
        }
        try {
            LoginUser loginUser = SessionUtils.getLoginUserInfo(request);
            long programId = cpProgramService.saveProgram(programName, programResolution, programTemplateId, loginUser);
            if (programId == 0) {
                return new JsonResponse(ResponseConstant.CODE_FAIL, ProgramConstant.MSG_PROGRAM_EXITS);
            }
            if (programId == -1) {
                return new JsonResponse(ResponseConstant.CODE_FAIL, ProgramConstant.MSG_PROGRAM_TEMPLATE_NOT_EXITS);
            }
            if (programId > 0) {

                return new JsonResponse(ResponseConstant.CODE_SUCCESS, programId, ProgramConstant.MSG_SAVE_PROGRAM_SUCCESS);
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("CpProgramController saveProgram 创建节目失败: " + e.getMessage());
        }
        return new JsonResponse(ResponseConstant.CODE_FAIL, ProgramConstant.MSG_SAVE_PROGRAM_FAIL);
    }

    /**
     * 根据节目ID获取节目
     *
     * @param programId 节目ID
     * @param request   请求
     * @return 页面
     */
    @ResponseBody
    @RequestMapping(value = "/get/{programId}")
    public Object getById(@PathVariable("programId") Long programId, HttpServletRequest request) {
        if (null == programId) {
            return new JsonResponse(ResponseConstant.CODE_FAIL, ProgramConstant.MSG_PROGRAM_ID_NOT_NULL);
        }
        try {
            CpProgramDTO cpProgramDTO = cpProgramService.selectByPrimaryKeyDTO(programId, request);
            if (null == cpProgramDTO) {
                return new JsonResponse(ResponseConstant.CODE_FAIL, ProgramConstant.MSG_PROGRAM_NOT_EXITS);
            }
            return new JsonResponse(ResponseConstant.CODE_SUCCESS, cpProgramDTO, ProgramConstant.MSG_QUERY_SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("CpProgramController getById 根据节目ID获取节目失败: " + e.getMessage());
        }
        return new JsonResponse(ResponseConstant.CODE_FAIL, ProgramConstant.MSG_QUERY_FAIL);
    }

    /**
     * 清除节目不通过原因
     *
     * @param programId 节目ID
     * @param request   请求
     * @return
     */
    @RequestMapping(value = "/cleanReason")
    @ResponseBody
    public Object cleanReason(Long programId, HttpServletRequest request) {
        try {
            //获取用户信息
            User user = (User) request.getSession().getAttribute(RequestConstant.SESSION_KEY_USER);
            if (user == null) {
                return new JsonResponse(ResponseConstant.CODE_FAIL, UserConstant.USER_NOT_LOGIN);
            }
            if (null == programId) {
                return new JsonResponse(ResponseConstant.CODE_FAIL, ProgramConstant.MSG_PROGRAM_ID_NOT_NULL);
            }
            int row = cpProgramService.cleanProgramNoPassReason(user.getCompanyCode(), programId);
            if (row > 0) {
                return new JsonResponse(ResponseConstant.CODE_SUCCESS, ProgramConstant.MSG_UPDATE_PROGRAM_SUCCESS);
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("CpProgramController cleanProgramNoPassReason 清除节目不通过原因失败：" + e.getMessage());
        }
        return new JsonResponse(ResponseConstant.CODE_FAIL, ProgramConstant.MSG_UPDATE_PROGRAM_FAIL);
    }


    /**
     * 商家节目的终端列表分页(从终端删除节目时的终端列表)
     *
     * @param programVersion 节目版本号
     * @param deviceCode     终端机器码
     * @param model          模型
     * @param pageNum        当前页
     * @param pageSize       每页条数
     * @return 列表页面
     */
    @RequestMapping(value = "/listDeleteProgramFromDeviceByPage")
    public String listProgramDeviceByPage(String programVersion, String deviceCode, Model model,
                                          Integer pageNum, Integer pageSize, HttpServletRequest request) {
        User user = (User) request.getSession().getAttribute(RequestConstant.SESSION_KEY_USER);
        pageNum = (pageNum == null ? PageConstant.DEFAULT_PAGE_NUM : pageNum);
        pageSize = (pageSize == null ? PageConstant.DEFAULT_PAGE_SIZE : pageSize);
        try {
            Page<CpProgramDeviceListVO> page = cpProgramService.listProgramDeviceByPage(user.getCompanyCode(),
                    programVersion, deviceCode, pageNum, pageSize);
            model.addAttribute("programVersion", programVersion);
            model.addAttribute("deviceCode", deviceCode);
            model.addAttribute("pageNum", pageNum);
            model.addAttribute("pageSize", pageSize);
            model.addAttribute("result", page.getResult());
            model.addAttribute("total", page.getTotal());
            CpProgramDeviceCountVO cpProgramDeviceCountVO = cpProgramService.getProgramDeviceCount(user.getCompanyCode(), programVersion, deviceCode);
            model.addAttribute("countResult", cpProgramDeviceCountVO);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("CpProgramController listProgramDeviceByPage fail:" + e.getMessage());
        }
        return "cp/cp_program_device_list";
    }

    /**
     * 商家节目的终端列表分页(下载详情)
     *
     * @param programVersion 节目版本号
     * @param deviceCode     终端机器码
     * @param model          模型
     * @param pageNum        当前页
     * @param pageSize       每页条数
     * @return 列表页面
     */
    @RequestMapping(value = "/listDeviceDownloadByPage")
    public String listDeviceDownloadByPage(String programVersion, String deviceCode, Model model,
                                           Integer pageNum, Integer pageSize, HttpServletRequest request) {
        User user = (User) request.getSession().getAttribute(RequestConstant.SESSION_KEY_USER);
        pageNum = (pageNum == null ? PageConstant.DEFAULT_PAGE_NUM : pageNum);
        pageSize = (pageSize == null ? PageConstant.DEFAULT_PAGE_SIZE : pageSize);
        try {
            Page<CpProgramDeviceListVO> page = cpProgramService.listProgramDeviceByPage(user.getCompanyCode(),
                    programVersion, deviceCode, pageNum, pageSize);
            model.addAttribute("result", page.getResult());
            model.addAttribute("pageNum", pageNum);
            model.addAttribute("pageSize", pageSize);
            model.addAttribute("total", page.getTotal());
            model.addAttribute("programVersion", programVersion);
            model.addAttribute("deviceCode", deviceCode);
            CpProgramDeviceCountVO cpProgramDeviceCountVO = cpProgramService.getProgramDeviceCount(
                    user.getCompanyCode(), programVersion, deviceCode);
            model.addAttribute("countResult", cpProgramDeviceCountVO);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("CpProgramController listDeviceDownloadByPage fail:" + e.getMessage());
        }
        return "cp/cp_program_download_detail";
    }

    /**
     * 删除节目
     *
     * @param programId 节目主键
     * @param request   请求
     * @return JsonResponse
     */
    @RequestMapping(value = "/deleteProgram")
    @ResponseBody
    public Object deleteProgram(Long programId, HttpServletRequest request) {
        if (null == programId) {
            return new JsonResponse(ResponseConstant.CODE_FAIL, ProgramConstant.MSG_PROGRAM_ID_NOT_NULL);
        }
        try {
            Program program = cpProgramService.selectByPrimaryKey(programId);
            if (null == program) {
                return new JsonResponse(ResponseConstant.CODE_FAIL, ProgramConstant.MSG_PROGRAM_NOT_EXITS);
            }
            if (ProgramConstant.PROGRAM_STATUS_APPROVED.equals(program.getProgramStatus())) {
                //已审批不能从这里删除,只能从终端删除
                return new JsonResponse(ResponseConstant.CODE_FAIL, ProgramConstant.MSG_APPROVED_PROGRAM_MUST_DELETE_FROM_DEVICE);
            }
            int effectRow = cpProgramService.deleteByProgramVersion(program.getProgramVersion(), request);
            if (effectRow == 1) {
                return new JsonResponse(ResponseConstant.CODE_SUCCESS, ProgramConstant.MSG_DELETE_PROGRAM_SUCCESS);
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("CpProgramController deleteProgram delete fail: " + e.getMessage());
        }
        return new JsonResponse(ResponseConstant.CODE_FAIL, ProgramConstant.MSG_DELETE_PROGRAM_FAIL);
    }

    /**
     * 批量删除节目的终端（如果所有终端都已删除该节目则将节目状态改为‘已过期’）
     *
     * @param programVersion 节目版本号
     * @param deviceCodes    终端code(多个以英文逗号隔开)
     * @param request        请求
     * @return JsonResponse
     */
    @RequestMapping(value = "/batchDeleteDeviceFromProgram")
    @ResponseBody
    public Object batchDeleteDeviceFromProgram(String programVersion, String deviceCodes, HttpServletRequest request) {
        if (StringUtils.isBlank(programVersion)) {
            return new JsonResponse(ResponseConstant.CODE_FAIL, ProgramConstant.MSG_PROGRAM_VERSION_NOT_NULL);
        }
        if (StringUtils.isBlank(deviceCodes)) {
            return new JsonResponse(ResponseConstant.CODE_FAIL, ProgramConstant.MSG_DEVICE_CODE_NOT_NULL);
        }
        try {
            boolean result = cpProgramService.batchDeleteDeviceFromProgram(programVersion, deviceCodes, request);
            if (result) {
                return new JsonResponse(ResponseConstant.CODE_SUCCESS, ProgramConstant.MSG_BATCH_DELETE_FROM_PROGRAM_SUCCESS);
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("CpProgramController batchDeleteDeviceFromProgram fail: " + e.getMessage());
        }
        return new JsonResponse(ResponseConstant.CODE_FAIL, ProgramConstant.MSG_BATCH_DELETE_FROM_PROGRAM_FAIL);
    }


    /**
     * 批量从终端删除节目（如果所有终端都已删除该节目则将节目状态改为‘已过期’）
     *
     * @param programVersions 节目版本号(多个以英文逗号隔开)
     * @param deviceCode      终端code
     * @param request         请求
     * @return JsonResponse
     */
    @RequestMapping(value = "/batchDeleteProgramFromDevice")
    @ResponseBody
    public Object batchDeleteProgramFromDevice(String programVersions, String deviceCode, HttpServletRequest request) {
        if (StringUtils.isBlank(programVersions)) {
            return new JsonResponse(ResponseConstant.CODE_FAIL, ProgramConstant.MSG_PROGRAM_VERSION_NOT_NULL);
        }
        if (StringUtils.isBlank(deviceCode)) {
            return new JsonResponse(ResponseConstant.CODE_FAIL, ProgramConstant.MSG_DEVICE_CODE_NOT_NULL);
        }
        try {
            boolean result = cpProgramService.batchDeleteProgramFromDevice(programVersions, deviceCode, request);
            if (result) {
                return new JsonResponse(ResponseConstant.CODE_SUCCESS, ProgramConstant.MSG_BATCH_DELETE_FROM_PROGRAM_SUCCESS);
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("CpProgramController batchDeleteProgramFromDevice fail: " + e.getMessage());
        }
        return new JsonResponse(ResponseConstant.CODE_FAIL, ProgramConstant.MSG_BATCH_DELETE_FROM_PROGRAM_FAIL);
    }
}
